package com.example.interceptor;

/**
 * Created with IntelliJ IDEA.
 * User: tao95
 * Date: 2017/5/7
 * Time: 19:38
 * To change this template use File | Settings | File Templates.
 * Description:
 */


import com.example.model.Admin;
import com.example.util.MD5Util;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;

import static com.example.util.Constants.*;


@Component
public class LoginInterceptor extends HandlerInterceptorAdapter {

    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {
        if (!handler.getClass().isAssignableFrom(HandlerMethod.class)) {
            return true;
        }
        handlerSession(request);
        HttpSession session = request.getSession();
        final HandlerMethod handlerMethod = (HandlerMethod) handler;
        final Method method = handlerMethod.getMethod();
        final Class<?> clazz = method.getDeclaringClass();
        if (clazz.isAnnotationPresent(Auth.class) ||
                method.isAnnotationPresent(Auth.class)) {
            if(request.getAttribute(USER_CODE_SESSION_KEY) == null){
                //throw new Exception();
                session.setAttribute("admin",null);
                session.setAttribute("sessionFlag",null);
                request.getRequestDispatcher("/").forward(request, response);
                return false;
            }else{
                return true;
            }
        }

        return true;

    }
    public void  handlerSession(HttpServletRequest request) {
        HttpSession session = request.getSession();
        Admin admin = (Admin)session.getAttribute("admin");
        if(admin == null){
            return ;
        }
        String sessionFlag = (String) session.getAttribute("sessionFlag");
        if(sessionFlag == null || !sessionFlag.equals(MD5Util.encodeToHex(admin.getPhone()+admin.getPassword()))){
            return ;
        }
        request.setAttribute(SESSION_KEY,MD5Util.encodeToHex(admin.getPhone()+admin.getPassword()));
        String userCode = admin.getUserName();
        if (userCode != null) {
            request.setAttribute(USER_CODE_SESSION_KEY, userCode);
        }
        String phone = admin.getPhone();
        if (phone != null) {
            request.setAttribute(MOBILE_NUMBER_SESSION_KEY, phone);
        }
        return ;
    }
}